#!/usr/bin/env pwsh

# FastAPI Server Script (Start/Stop)
# Save original working directory
$OriginalDir = Get-Location

# Get command line argument, default to start mode
$mode = "start"
if ($args.Count -gt 0) {
    $mode = $args[0].ToLower()
}

# Function to check and start dependencies if needed
function Check-And-Start-Dependencies {
    # Check if MySQL is running
    if (-not (docker ps | Select-String -Pattern "mysql")) {
        Write-Host "MySQL is not running. Starting MySQL..." -ForegroundColor Yellow
        & "$PSScriptRoot\01manage_mysql.ps1"
    }
    
    # Check if Redis is running
    if (-not (docker ps | Select-String -Pattern "redis")) {
        Write-Host "Redis is not running. Starting Redis..." -ForegroundColor Yellow
        & "$PSScriptRoot\02manage_redis.ps1"
    }
}

if ($mode -eq "start") {
    Write-Host "Starting FastAPI Server..." -ForegroundColor Yellow
    
    # Check and start dependencies
    Check-And-Start-Dependencies

    # Skipping container cleanup as per requirements
    Write-Host "Skipping container cleanup, starting FastAPI server container directly..." -ForegroundColor Yellow

    # Start FastAPI server container without rebuilding
    Write-Host "Starting FastAPI server container..." -ForegroundColor Yellow
    docker-compose -f "$PSScriptRoot\..\server\8-docker-compose-fastapi.yml" up -d
    Write-Host "FastAPI Server started successfully!" -ForegroundColor Green
    Write-Host "You can check status with: docker-compose -f .\server\8-docker-compose-fastapi.yml ps" -ForegroundColor White
    Write-Host "To stop the service, run: ./08manage_fastapi-server.ps1 stop" -ForegroundColor White
} elseif ($mode -eq "stop") {
    Write-Host "Stopping FastAPI Server..." -ForegroundColor Yellow
    # Stop FastAPI server container using docker-compose stop
    docker-compose -f "$PSScriptRoot\..\server\8-docker-compose-fastapi.yml" stop
    Write-Host "FastAPI Server stopped successfully!" -ForegroundColor Green
    Write-Host "To start the service again, run: ./08manage_fastapi-server.ps1 start" -ForegroundColor White
} else {
    Write-Host "Invalid mode. Please use 'start' or 'stop'." -ForegroundColor Red
    Write-Host "Example: ./08manage_fastapi-server.ps1 start" -ForegroundColor White
    Write-Host "Example: ./08manage_fastapi-server.ps1 stop" -ForegroundColor White
    # 恢复原始工作目录后退出
    Set-Location $OriginalDir
    exit 1
}

# Return to original working directory
Set-Location $OriginalDir
Write-Host "Returned to original directory: $OriginalDir" -ForegroundColor White
